package com.xaicode.template.batch.job.file;

import org.springframework.batch.core.Job;
import org.springframework.batch.core.Step;
import org.springframework.batch.core.configuration.annotation.JobBuilderFactory;
import org.springframework.batch.core.configuration.annotation.StepBuilderFactory;
import org.springframework.batch.item.ItemReader;
import org.springframework.batch.item.json.JacksonJsonObjectReader;
import org.springframework.batch.item.json.JsonItemReader;
import org.springframework.context.annotation.Bean;
import org.springframework.core.io.ClassPathResource;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

/**
 * json file: classpath:file/jobFile.json
 *
 * @author beborn
 * @date 2022/1/6 0006 11:05
 */
@Component
public class JSONFileItemReaderDemo {

    @Resource
    private JobBuilderFactory jobBuilderFactory;

    @Resource
    private StepBuilderFactory stepBuilderFactory;

    @Bean
    public Job jsonFileItemReaderJob() {
        return jobBuilderFactory.get("jsonFileItemReaderJob")
                .start(step())
                .build();
    }

    private Step step() {
        return stepBuilderFactory.get("step")
                .<TransData, TransData>chunk(2)
                .reader(jsonItemReader())
                .writer(list -> list.forEach(System.out::println))
                .build();
    }

    private ItemReader<TransData> jsonItemReader() {
        ClassPathResource resource = new ClassPathResource("file/jobFile.json");
        JacksonJsonObjectReader<TransData> jacksonJsonObjectReader = new JacksonJsonObjectReader<>(TransData.class);
        JsonItemReader<TransData> reader = new JsonItemReader<>(resource, jacksonJsonObjectReader);
        reader.setName("testDataJsonItemReader");
        reader.setStrict(false);
        return reader;
    }

}
